const superagent = require('superagent');
require('superagent-proxy')(superagent);
const {setCookieFrom} = require("./cookieTools");
global.proxy = "http://jsengine:jsengine123456@iproxy.fly.17usoft.com:8080";
// let proxy = "socks5://127.0.0.1:10808";
// let proxy = null;
// set('Accept', 'text/html,text/javascript')
// sa.set('Content-Type', 'application/json');

async function request(method, url, headers, data, retryCount, timeout, need_body, image, needProxy=true, proxy_config=null, needHeaders=false) {
    const sa = superagent(method, url).redirects(0);
    // const sa = superagent(method, url);
    try {
        headers['Cookie'] = document.cookie;
    }catch (err){}

    Object.keys(headers).forEach((key)=>{
        sa.set(key, headers[key]);
    })
    let theProxy;
    if (!needProxy){
        theProxy = null;
    }else {
        if (proxy_config){
            theProxy = proxy_config;
        }else{
            theProxy = proxy;
        }

    }
    let res;
    let respHeaders= null;

    try {
        if (image) {
            res = await sa.send(data).proxy(theProxy).timeout(timeout).buffer(true).parse(superagent.parse.image);
        } else {
            res = await sa.send(data).proxy(theProxy).timeout(timeout);
        }
        if (res.statusCode !== 200 && res.statusCode !== 204 && res.statusCode !== 201 && res.statusCode !== 401) {
            // 204 nocontent 兼容腾讯滑块
            // 201 nocontent 兼容Akamai
            // 201 nocontent 兼容瑞数
            throw "网络错误";
        }
        respHeaders = res.headers;
        setCookieFrom(respHeaders, url);
        if (need_body) {
            return res.body;
        } else {
            const resText = res.text ? res.text : Object.keys(res.body).length === 0 ? "": res.body.toString();
            if (needHeaders){
                return  {
                    resText: resText,
                    headers: res.headers,
                    url:url
                }
            }
            return resText;
        }

    } catch (err) {
        let resText = '';
        if (err.headers){
            respHeaders = err.headers;
        }else if(err.response && err.response.headers){
            respHeaders = err.response.headers;
        }
        if (respHeaders){
            setCookieFrom(respHeaders, url);
        }
        if (err.statusCode === 200){
            resText = err.rawResponse;
        }
        if (err.status === 302 && respHeaders) {
            url = respHeaders.location;
            return request(method, url, headers, data, retryCount, timeout, need_body, image, needProxy, proxy_config, needHeaders);
        }
        if ((err.status === 403 || err.status === 503 || err.status === 412 || err.status === 502)&& err.response && err.response.text) {
            if (err.status === 502){
                //兼容去哪儿h5
                resText = '';

            }else {
                resText = err.response.text;
            }
        }
        if (needHeaders) {
            return {
                resText: resText,
                headers: respHeaders,
                url: url
            }
        }else {
            return resText;
        }
    }
}


async function get(url, headers, retryCount=1, timeout=1500, need_body=false, image=false, needProxy=true, proxy_config=null, needHeaders=false){
    return request('GET', url, headers, null, retryCount, timeout, need_body, image, needProxy, proxy_config, needHeaders)
}

async function post(url, data, headers, retryCount=1, timeout=1500, need_body=false, needProxy=true, proxy_config=null, needHeaders=false){
    return request('POST', url, headers, data, retryCount, timeout, need_body, false, needProxy, proxy_config, needHeaders)
}

module.exports = {
    request: request,
    get: get,
    post: post,
    proxy:proxy,
}
